import axios, { type Canceler } from "axios";
import { ElMessageBox, ElMessage } from "element-plus";



//创建axios
const http = axios.create({
    baseURL: import.meta.env.ENV_BASE_URL,
    timeout: 60000,
});

//请求拦截
const getRequestMap = new Map<string | number, Canceler>();
http.interceptors.request.use(
    (config) => {
        //请求拦截

        return config;
    },
    (err) => {
        return Promise.reject(err);
    }
);

// 响应拦截
http.interceptors.response.use(
    (res) => {
        console.log(res);

        getRequestMap.delete(res.config.url as string);
        if (res.status === 200) {
            if (res.data.code == 401) {
                return Promise.reject("No auth;");
            }
            if (res.data.code == 0) {
                return Promise.resolve(res.data.data);
            } else {
                let { message } = res.data;
                ElMessage.error("错误：" + message + '54545646');
                return Promise.reject(res.data);
            }
        }

        return Promise.reject(res);
    },
    (err) => {
        getRequestMap.delete(err.config?.url || "");
        if (err && err.response) {
            switch (err.response.status) {
                case 400:
                    err.message = "请求出错";
                    break;
                case 401:
                    break;
                case 403:
                    err.message = "拒绝访问";
                    break;
                // 404请求不存在
                case 404:
                    err.message = "请求错误,未找到该资源";
                    break;
                case 500:
                    err.message = "服务器端出错";
                    break;
            }
        } else if ("ERR_CANCELED" == err.code) {
            return Promise.reject(err);
        } else {
            err.message = "连接服务器失败";
        }
        ElMessage.error(err.message);
        return Promise.reject(err.response);
    }
);
export const get = (url: string, params?: any): any => http.get(url, { params });
export const post = (url: string, data?: any): any => http.post(url, data);

export default http;
